
from saas.const import *
from saas.misc import *
from saas.crypto import *
import struct


def pkt_unpack( pkt ):
	## pull apart the packet.
	hash        = pkt[0:32]
	( magic_id , trans_id , type , payload_len , reserved0 , reserved1 ) = struct.unpack( '> I I H H H H' , pkt[32:48] )
	if ( payload_len > 0 ):
		payload = pkt[48:48+payload_len]
	else:
		payload = ''

	## verify the packets integrity.
	if sha256( pkt[32:48+payload_len] ) != hash:
		return False

	## double check that this packet is valid.
	if magic_id != SAAS_MAGIC_REQ:
		return False

	return ( trans_id , type , payload_len , payload )



def pkt_pack( trans_id , pkttype , payload ):
	pkt = struct.pack( '> I I H H H H' , SAAS_MAGIC_RESP , trans_id , pkttype , len( payload ) , 0 , 0 ) + payload
	return sha256( pkt ) + pkt



